package cn.tom.service.impl;

import cn.tom.entity.User;
import cn.tom.mapper.MyUserMapper;
import cn.tom.service.MyUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class MyUserServiceImpl implements MyUserService, UserDetailsService {

    @Autowired
    MyUserMapper myUserMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    /**
     * Logger输出
     */
    private Logger log
            = LoggerFactory.getLogger(cn.tom.tool.Log.class);

    @Override
    public UserDetails loadUserByUsername(String account)
            throws UsernameNotFoundException {
        QueryWrapper queryWrapper = new QueryWrapper();     //创建一个查询条件的类对象
        queryWrapper.eq("account", account);         //查询条件username
        UserDetails u = myUserMapper.selectOne(queryWrapper);   //执行条件查询
        log.info("用户信息 = " + u);
        return u;
    }

    /**
     * 添加一个管理员
     */
    @Override
    public int add(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));   //密码加密
        int insert = myUserMapper.insert(user);
        return insert;
    }

    /**
     * 更新管理员信息
     */
    @Override
    public int update(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));   //密码加密
        int i = myUserMapper.updateById(user);
        return i;
    }

    /**
     * 删除管理员
     */
    @Override
    public int del(Integer id) {
        int i = myUserMapper.deleteById(id);
        return i;
    }
}
